package com.touchapk.javafx;

import java.io.File;
import java.io.FileInputStream;
import java.util.Comparator;
import java.util.Properties;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;

public class FileTreeItem extends TreeItem<File>  {
	private boolean isLeaf;
	private boolean isFirstTimeChildren = true;
	private boolean isFirstTimeLeaf = true;
	private boolean isRoot;//0 不是 1 是 2 是第二层
	public FileTreeItem(File file,boolean isRoot) {
		super(file);
		this.isRoot=isRoot;
	}

	@Override
	public ObservableList<TreeItem<File>> getChildren() {

		if (isFirstTimeChildren) {
			isFirstTimeChildren = false;

			super.getChildren().setAll(buildChildren(this));

		}
		return super.getChildren();

	}

	@Override
	public boolean isLeaf() {
		if (isFirstTimeLeaf) {
			isFirstTimeLeaf = false;
			File f = (File) getValue();
			isLeaf = f.isFile();
		}

		return isLeaf;
	}
	
	private ObservableList<TreeItem<File>> buildChildren(TreeItem<File> TreeItem) {
		File f = TreeItem.getValue();
		if (f != null && f.isDirectory()) {
			File[] files = f.listFiles();

			if (files != null) {
				
				ObservableList<TreeItem<File>> children = FXCollections.observableArrayList();

				for (File childFile : files) {
					if(this.isRoot&&childFile.isDirectory()){
						String projectFilePath=childFile.getAbsolutePath()+"\\.project";
						File pFile=new File(projectFilePath);
						if(pFile.exists()){
							Properties pro = new Properties();
							
							try {
								FileInputStream in = new FileInputStream(pFile);
								pro.load(in);
								String projectName=pro.getProperty("projectName");
								String status=pro.getProperty("status");
								if("1".equals(status)&&projectName!=null){
									FileTreeItem ft = new FileTreeItem(childFile,false);
									children.add(ft);
								}
							} catch (Exception e) {}
						}
					}else if(!this.isRoot){
						
							FileTreeItem ft = new FileTreeItem(childFile,false);
							//Event.fireEvent(ft, new TreeItem.TreeModificationEvent(TreeItem.valueChangedEvent(), ft, ft.getValue()));
							children.add(ft);
						
					}
				
				}
				children.sort(new Comparator<TreeItem<File>>(){
					@Override
					public int compare(TreeItem<File> o1,TreeItem<File> o2) {
						if(o2.getValue().isDirectory()&&!o1.getValue().isDirectory()){
							return 1;
						}
						
						if(o1.getValue().getName().startsWith(".")||o2.getValue().getName().startsWith(".")){
							return o2.getValue().getName().compareTo(o1.getValue().getName());
						}
						
						return o1.getValue().getName().compareTo(o2.getValue().getName());
						
					}
		        });
				return children;
			}
		}

		return FXCollections.emptyObservableList();
	}

	
}